Apache CXF框架的单元测试需要内置Jetty容器
org.eclipse.jetty
jetty-webapp
${jetty.version}
test
下面是一个基于Spring框架的Apache CXF测试示例
applicationContext-restful.xml
DemoRestful.java
@Path("demo")
@Component("demoRestful")
public class DemoRestful {
@POST
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String test(String str) {
return "This is a cxf restful test method.";
}
}
DemoRestfulTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = Application.class)
public class DemoRestfulTest {
public final String REST_SERVICE_URL = "http://localhost:8088/rest";
public final Server server = new Server(8088);
@Before
public void before() {
// Register and map the dispatcher servlet
final ServletHolder servletHolder = new ServletHolder(new CXFServlet());
final ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.addServlet(servletHolder, "/rest/*");
context.addEventListener(new ContextLoaderListener());
context.setInitParameter(
"contextConfigLocation",
"classpath*:/applicationContext-restful.xml");
server.setHandler(context);
try {
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
@After
public void after() {
try {
server.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void test() throws Exception {
JSONObject json = new JSONObject();
json.put("name", "test");
WebClient client = WebClient.create(REST_SERVICE_URL);
Response response = client.path("/demo/test")
.accept("application/json")
.type("application/json; ")
.post(json.toJSONString());
Assert.assertEquals(response.getStatus(), 200);
}
}
|